//
//  CollectViewController.m
//  DongChiDaChiProject1
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "CollectViewController.h"
#import <AVOSCloud/AVOSCloud.h>
#import "UserCollectData.h"
#import "AllNextModelTwo.h"
#import "AllNextTableViewCell.h"
#import "AllKindNextDetailViewController.h"
#import "UserManager.h"


@interface CollectViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

// 建立一个数组存放model
@property (nonatomic, strong) NSMutableArray *modelArray;

// 建立一个数组存放步骤数组
@property (nonatomic, strong) NSMutableArray *allStepArray;

@end

@implementation CollectViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = self.titleName;
    
    // 建立数据源
    [self setUpData];
    
  
    [self addBar];
}

#pragma mark - 添加bar
- (void)addBar
{
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"我的" style:UIBarButtonItemStylePlain target:self action:@selector(returnToLast:)];
    leftItem.tintColor = [UIColor colorWithHue:0.8 saturation:1 brightness:0.7 alpha:1];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTranslucent:NO];
}

- (void)returnToLast:(UIBarButtonItem *)barItem
{
    [self.navigationController popViewControllerAnimated:YES];
}



#pragma mark - 视图将要出现
- (void)viewWillAppear:(BOOL)animated
{
    // 隐藏tabbar
    self.tabBarController.tabBar.hidden = YES;
    
    
}


// 建立数据源
- (void)setUpData
{
    
    
    self.allStepArray = [NSMutableArray array];
    self.modelArray = [NSMutableArray array];
    
    // 从LeanCloud上获取数据
    AVQuery *query = [UserCollectData query];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        for (UserCollectData *userData in objects) {
            if ([userData.userName isEqualToString:[[UserManager shareUserManagerHandle] getUserName]]) {
                // 临时的字典
                NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
                [tempDic setValue:userData.albums forKey:@"albums"];
                [tempDic setValue:userData.burden forKey:@"burden"];
                [tempDic setValue:userData.imtro forKey:@"imtro"];
                [tempDic setValue:userData.ingredients forKey:@"ingredients"];
                [tempDic setValue:userData.title forKey:@"title"];
                AllNextModelTwo *model = [[AllNextModelTwo alloc] init];
                [model setValuesForKeysWithDictionary:tempDic];
                [self.modelArray addObject:model];
                // 存放stepArray
                [self.allStepArray addObject:userData.stepArray];
            }
           
        }
        NSLog(@"self.modelArray = %@, self.allStepArray = %@", self.modelArray, self.allStepArray);
        // 添加视图
        [self addSubTableView];
        
        if (error == nil) {
            // 说明没有错误
            if (self.modelArray.count == 0) {
                // 说明没有数据了
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"亲！还没有收藏哦，快去收藏把！" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *queDingAlert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self.navigationController popViewControllerAnimated:YES];
                }];
                [alertController addAction:queDingAlert];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        
        if (error != nil) {
            // 说明有错误
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"通知" message:@"该功能需要联网后才能使用" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
            [alertView show];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [alertView dismissWithClickedButtonIndex:0 animated:YES];
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    }];
    
   
    
}


- (void)addSubTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:(UITableViewStylePlain)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   
    return self.modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"AllNextTableViewCell";
    AllNextTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[AllNextTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
    if (self.modelArray.count > indexPath.row) {
        cell.allNextModel = (AllNextModel *)self.modelArray[indexPath.row];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100 * kWidthFitParameter;
}

#pragma mark - 点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    AllKindNextDetailViewController *allKindNextDetailVC = [[AllKindNextDetailViewController alloc] init];
    if (self.modelArray.count > indexPath.row) {
        allKindNextDetailVC.allNextModel = self.modelArray[indexPath.row];
        allKindNextDetailVC.fetchArray = self.allStepArray[indexPath.row];
    }
    
    
    [self.navigationController pushViewController:allKindNextDetailVC animated:YES];
}

#pragma mark - 删除的方法
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

// 删除
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"indexpath.row = %ld", indexPath.row);
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // 取出对应model的标题
        NSString *title = [self.modelArray[indexPath.row] valueForKey:@"title"];
        
        // 执行删除的方法
        // 删除tableview上的对应项
        [self.modelArray removeObjectAtIndex:indexPath.row];
        [self.allStepArray removeObjectAtIndex:indexPath.row];
        // 刷新界面
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        
        // 删除leanCloud上的数据
        // 从LeanCloud上获取数据
        AVQuery *query = [UserCollectData query];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            
            
            for (UserCollectData *tempData in objects) {
               
               // NSLog(@"title = %@", title);
                if ([tempData.title isEqualToString: title]) {
                    NSLog(@"tempData.objectId = %@", tempData.objectId);
                    // 删除
                    UserCollectData *deleteData = [UserCollectData objectWithoutDataWithObjectId:tempData.objectId];
                    [deleteData deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        NSLog(@"删除成功");
                    }];
                }
            }
           
            
        }];

        
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
